package org.eclipse.ui.articles.views;

import gsoc.p2.activator.MyActivator;
import gsoc.p2.browser.CustomBrowserFunction;

import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.BrowserFunction;
import org.eclipse.swt.browser.LocationAdapter;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.ProgressAdapter;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
import org.osgi.framework.BundleContext;

public class P2BrowserView extends ViewPart {

	// private Label label;
	private Browser browser;
	
	public P2BrowserView() {
		super();
	}

	@Override
	public void createPartControl(Composite parent) {
		
		// TODO: how to get bundle context here?
		BundleContext context = MyActivator.getContext();
		if (context != null) {
			System.out.println("CONTEXT not null");
		} else {
			System.out.println("CONTEXT is NULL.");
		}
		
		// instantiate browser
		try {
			browser = new Browser(parent, SWT.NONE);
		} catch (SWTError e) {
			System.out.println("Error instantiating browser: " + e.getMessage());
		}
		browser.setText(createHTML());
		final BrowserFunction browserFunction = new CustomBrowserFunction(browser, "theJavaFunction");
		browser.addProgressListener(new ProgressAdapter() {
			public void completed (ProgressEvent event) {
				browser.addLocationListener (new LocationAdapter () {
					public void changed (LocationEvent event) {
						browser.removeLocationListener (this);
						System.out.println ("left java function-aware page, so disposed CustomFunction");
						browserFunction.dispose ();
					}
				});
			}
		}
		);
	}

	@Override
	public void setFocus() {
		browser.setFocus();
	}

	private static String createHTML () {
		StringBuffer buffer = new StringBuffer ();
		buffer.append ("<html>\n");
		buffer.append ("<head>\n");
		buffer.append ("<script language=\"JavaScript\">\n");
		buffer.append ("function function1() {\n");
		buffer.append ("    var result;\n");
		buffer.append ("    try {\n");
		buffer.append ("        result = theJavaFunction(12, false, null, [3.6, ['swt', true]], 'eclipse');\n");
		buffer.append ("    } catch (e) {\n");
		buffer.append ("        alert('a java error occurred: ' + e.message);\n");
		buffer.append ("        return;\n");
		buffer.append ("    }\n");
		buffer.append ("    for (var i = 0; i < result.length; i++) {\n");
		buffer.append ("        alert('returned ' + i + ': ' + result[i]);\n");
		buffer.append ("    }\n");
		buffer.append ("}\n");
		buffer.append ("</script>\n");
		buffer.append ("</head>\n");
		buffer.append ("<body>\n");
		buffer.append ("<input id=button type=\"button\" value=\"Push to Invoke Java\" onclick=\"function1();\">\n");
		buffer.append ("<p><a href=\"http://www.eclipse.org\">go to eclipse.org</a>\n");
		buffer.append ("</body>\n");
		buffer.append ("</html>\n");
		return buffer.toString ();
	}
}
